import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class UdpChat
{
    public static boolean ipCheck(String str)
    {
        String[] ipStringArray = str.split("\\.");
        if (ipStringArray.length == 4)
        {
            byte[] ipArray = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                if (Integer.parseInt(ipStringArray[i]) <= 255 && Integer.parseInt(ipStringArray[i]) >= 0)
                {
                    ipArray[i] = (byte) Integer.parseInt(ipStringArray[i]);
                }
                else
                    return false;
            }
            return true;

        }
        else
            return false;
    }
    
    public static boolean isNumeric(String str)
    {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches())
        {
            return false;
        }
        return true;
    }

    public static boolean isPortNumber(String str)
    {
        if (isNumeric(str))
        {
            int port = Integer.parseInt(str);
            if (port <= 65535 && port >= 1024)
            {
                return true;// TODO: initiate the server
            }
        }
        return false;
    }

    public static void main(String[] args)
    {
        if (args.length != 2 && args.length != 5)
        {
            System.out.println("ERROR Incorrect command");
            return;
        }
        if (args[0].equals("-s"))
        {
            if (isPortNumber(args[1]))
            {
                System.out.println("Initiate the server");
                Server server = new Server(Integer.parseInt(args[1]));
                server.run();
                return;// TODO: initiate the server
            }
            else
            {
                System.out.println("ERROR server port number");
                return;
            }
        }
        if (args[0].equals("-c"))
        {
            if (ipCheck(args[2]) == false){
                System.out.println("ERROR server-ip format");
                return;
            }
            
            if (isPortNumber(args[3]) && isPortNumber(args[4]))
            {
                System.out.println("Initiate the communication to the server");
                Client client = new Client(args[1],args[2],Integer.parseInt(args[3]),Integer.parseInt(args[4]));
                client.run();
            }
                
            else
            {
                System.out.println("ERROR port number");
            }

        }
        else
        {
            System.out.println("ERROR -s or -c");
            return;
        }
    }
}
 